﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web.Script.Serialization;
using Kooboo.Commerce.AddIn;
using Kooboo.IoC;
using System.ComponentModel.Composition;

namespace Kooboo.Commerce.Repositories
{
    [Export(typeof(IValidationRule))]
    public partial  class ValidationRule:IValidationRule
    {

        #region IValidationRule Members

        List<ValidatorParameter> _Parameters2;
        List<ValidatorParameter> IValidationRule.Parameters
        {
            get
            {
                if (this._Parameters2 == null)
                {
                    if (string.IsNullOrWhiteSpace(this.Parameters))
                    {
                        this._Parameters2 = new List<ValidatorParameter>();
                    }
                    else
                    {
                        var serializer = new JavaScriptSerializer();
                        this._Parameters2 = serializer.Deserialize<List<ValidatorParameter>>(this.Parameters);
                    }
                    
                }

                return this._Parameters2;
            }
            set
            {
                this._Parameters2 = value;
                if (value == null)
                {
                    this.Parameters = "[]";
                }
                else
                {
                    var serializer = new JavaScriptSerializer();
                    this.Parameters = serializer.Serialize(value);
                }
            }
        }


        IValidator _Validator;
        public IValidator Validator
        {
            get
            {
                if (this._Validator == null)
                {
                    this._Validator = ObjectContainer.CreateInstances<IValidator>()
                        .Where(i => i.Name == this.ValidatorName)
                        .FirstOrDefault();
                }

                return this._Validator;
            }
            set
            {
                this._Validator = value;
                this.ValidatorName = value.Name;
            }
        }

        #endregion
    }
}
